
#include <BSocket>
#include "member_BSocket.h"
#include "IGlobal.h"

using namespace BWE;

#define member					(*(member_BSocket*)_ptr)
#define member_allocate()		_ptr = new member_BSocket(this)
#define member_release()		delete (member_BSocket*)_ptr

BSocket::BSocket()
{
	member_allocate();
	app_sockets.append(this);
}
BSocket::~BSocket()
{
	if (member.sock)
	{
#ifdef _LINUX_
		::close(member.socket);
#endif
#ifdef _WINDOWS_SYSTEM_
		::closesocket(member.sock);
#endif
	}
	member_release();
}

bool BSocket::valid() const
{
	return member.sock > 0;
}

const BString& BSocket::address() const
{
	sockaddr_in addr =  member.addr;
	if (member.address.empty())
	{
		member.address << addr.sin_addr.S_un.S_un_b.s_b1 << '.';
		member.address << addr.sin_addr.S_un.S_un_b.s_b2 << '.';
		member.address << addr.sin_addr.S_un.S_un_b.s_b3 << '.';
		member.address << addr.sin_addr.S_un.S_un_b.s_b4;
	}
	return member.address;
}
int BSocket::port() const
{
	return member.addr.sin_port;
}

BSocket::Error BSocket::error() const
{
	return (Error)member.error;
}
const char* BSocket::errorStr() const
{
	return member.errorStr;
}

BSocket::State BSocket::state() const
{
	return member.state;
}

int BSocket::handle() const
{
	return member.sock;
}

